import {
  Controller,
  Post,
  UseGuards,
  Body,
  ConflictException,
  Get,
  Delete,
  Patch,
  Param,
  Query,
} from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { StudentsService } from './students.service';
import { CreateStudentDto } from './dto/create-student.dto';
import { MongoError } from 'mongodb';
import { DeleteStudentsDto } from './dto/delete-students.dto';
import { UpdateStudentDto } from './dto/update-student.dto';
import { GetStudentsQueryDto } from './dto/get-students-query.dto';

@Controller('students')
@UseGuards(AuthGuard())
export class StudentsController {
  constructor(private readonly stuentsService: StudentsService) {}

  @Post()
  async createStudent(@Body() createStudentDto: CreateStudentDto) {
    return await this.stuentsService
      .createStudent(createStudentDto)
      .catch((mongoError: MongoError) => {
        if (mongoError.code === 11000) {
          throw new ConflictException('请不要重复创建', '学生已经存在');
        }
        throw mongoError;
      });
  }

  @Get()
  async getStudents(@Query() getStudentsQueryDto: GetStudentsQueryDto) {
    return await this.stuentsService.getStudents(getStudentsQueryDto);
  }

  @Delete()
  async deleteStudents(@Body() deleteStudents: DeleteStudentsDto) {
    return await this.stuentsService.deleteStudents([
      ...new Set(deleteStudents.students),
    ]);
  }

  @Patch(':_id')
  async updateStudent(
    // tslint:disable-next-line: variable-name
    @Param('_id') _id: string,
    @Body() updateStudentDto: UpdateStudentDto,
  ) {
    return await this.stuentsService
      .updateStudent(_id, updateStudentDto)
      .catch((mongoError: MongoError) => {
        if (mongoError.code === 11000) {
          throw new ConflictException('不能修改成已有的学号', '学号已经存在');
        }
        throw mongoError;
      });
  }
}
